package org.itboys.ace.web;

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.itboys.admin.tools.AdminPermissionCheck;
import org.itboys.baseobject.entity.KeyValuesConfig;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.AceJsonPageUtils;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.weixin.entity.CommissionConfig;
import org.itboys.weixin.service.CommissionConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户管理
 * 
 * @author weisky
 *
 */
@RestController
@RequestMapping("/ace/admin/commission")
public class AceCommssionController extends BaseController {


	@Autowired
	private CommissionConfigService commissionConfigService;

	/**
	 * 点击佣金管理跳转页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/toVM")
	public ModelAndView listvm(HttpServletRequest request, HttpServletResponse response, Model model) {
        return new ModelAndView("/ace/admin/commission-list");
	}

	/**
	 * 分页查询
	 *
	 * @return
	 */
	@RequestMapping("/commission")
	public void list(HttpServletRequest request, HttpServletResponse response) {
        CommissionConfig dto = commissionConfigService.getConfig();
        Page<CommissionConfig> page = new Page<>();
        page.setData(Lists.newArrayList(dto));
        page.setTotal(1);
		AceJsonPageUtils.renderJsonPage(page.getTotal(), page.getData(), response);
	}

	/**
	 * 异步获取单个用户对象
	 *
	 * @param response
	 */
	@RequestMapping("/editCommission")
	public void getUser(HttpServletResponse response) {
		AjaxUtils.renderJson(response, commissionConfigService.getConfig());
	}

	/**
	 * 异步保存
	 */
	@RequestMapping("/save")
	@AdminPermissionCheck("adminUser:save")
	public void save(
			@ModelAttribute CommissionConfig dto,
			HttpServletRequest request,
			HttpServletResponse response) {
		try {
            if (dto.getId() == 0) {
                commissionConfigService.save(dto);
            } else {
                commissionConfigService.update(dto);
            }
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("save commission error", e);
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
}
